package com.study.dataStructure.leetcode.stack;

import jdk.nashorn.internal.ir.CallNode;

import java.util.LinkedList;
import java.util.List;

/**
 * @author tiny
 * @date 2021/11/15 21:56
 * @Description: https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/
 */
public class Solution2 {

    public int evalRPN(String[] tokens){
        Stack stack = new Stack();
        for (int i = 0; i < tokens.length; i++) {
            String token = tokens[i];
            if( "+".equals(token) ){
                Integer num2 = stack.pop();
                Integer num1 = stack.pop();
                stack.push(num1+num2);
            }else if("-".equals(token)){
                Integer num2 = stack.pop();
                Integer num1 = stack.pop();
                stack.push(num1-num2);
            }else if("*".equals(token)){
                Integer num2 = stack.pop();
                Integer num1 = stack.pop();
                stack.push(num1*num2);
            }else if("/".equals(token)){
                Integer num2 = stack.pop();
                Integer num1 = stack.pop();
                stack.push(num1/num2);
            }
            else{
                //是数字
                stack.push(Integer.parseInt(tokens[i]));
            }
        }
        return stack.peek();
    }

    class Stack{
        private List<Integer> link = new LinkedList<Integer>();

        void push(Integer num){
            link.add(num);
        }

        Integer pop(){
            return link.remove(link.size()-1);
        }

        Integer peek(){
            return link.get(link.size()-1);
        }
    }
}
